# -*- coding: UTF-8 -*-
import os
from Tkinter import *
#import Tkinter
from PIL import Image

import win32clipboard  
import win32gui  
import win32api  
import win32con  
import traceback  
  
from PIL import Image
from PIL import ImageTk
from cStringIO import StringIO  

from bs4 import BeautifulSoup
import urllib2
import requests
import re

import json

BASE_PATH = './photo/'

class SearchImg():
    def __init__(self,_root):
        self.keyword = ''
        self.urls = []
        self.parent = _root
        self.BaiduSearchUrl = 'https://image.baidu.com/search/acjson'
        self.savePath = ''
        
    # 展示搜索栏
    def ShowSearchUi(self):
        e = StringVar()
        entry = Entry(self.parent, textvariable = e)
        e.set('input your text here')
        entry.grid(row=0, column=0, columnspan=1, sticky=W + E + N + S, padx=10, pady=10);
        frame = Frame(self.parent)
        frame.grid(row=1, column=0, columnspan=8, sticky=W + E + N + S, padx=5, pady=5);
        findbtn = Button(self.parent, text='Search', relief=GROOVE, command =  lambda : self.searchEmotion(entry,frame,e,))
        findbtn.grid(row=0, column=1,columnspan=1, sticky=W + E + N + S, padx=10, pady=10);
        

    def searchEmotion(self,txtobj,frameob,e):
        self.keyword = txtobj.get()
        self.savePath = BASE_PATH + self.keyword+'/'
        e.set('')
        dataList = self.getManyPages(self.keyword, 1)
        self.getImg(dataList, self.savePath)
        #frameob.grid_forget()
        showAllEmotion(frameob, 30, self.keyword)
        #root.mainloop()
        
    def getKeyword(self):
        return self.keyword
        
    # 参数1:关键字，参数2:要下载的页数
    def getManyPages(self, keyword,pages):
        params=[]
        for i in range(30,30*pages+30,30):
            params.append({
                          'tn': 'resultjson_com',
                          'ipn': 'rj',
                          'ct': 201326592,
                          'is': '',
                          'fp': 'result',
                          'queryWord': keyword,
                          'cl': 2,
                          'lm': -1,
                          'ie': 'utf-8',
                          'oe': 'utf-8',
                          'adpicid': '',
                          'st': -1,
                          'z': '',
                          'ic': 0,
                          'word': keyword,
                          's': '',
                          'se': '',
                          'tab': '',
                          'width': '',
                          'height': '',
                          'face': 0,
                          'istype': 2,
                          'qc': '',
                          'nc': 1,
                          'fr': '',
                          'pn': i,
                          'rn': 30,
                          'gsm': '1e',
                          '1488942260214': ''
                      })
        urls = []
        for i in params:
            replacedQuoteJson = re.sub(r"\\x26([a-zA-Z]{2,6});", r"&\1;", requests.get(self.BaiduSearchUrl, params=i).content);
            urls = urls + re.findall('"thumbURL":"(.*?)"',replacedQuoteJson)
            print urls
        return urls

    # 参数2:指定保存的路径
    def getImg(self, dataList, localPath):
        if not os.path.exists(localPath):  # 新建文件夹
            os.makedirs(localPath)
        x = 0
        for one in dataList:
            print(u'正在下载：%s' % one)
            self.smallSize(one, localPath + '%d.jpg' % x)
            x += 1
    
    #直接从网络流获取，修改图片大小后保存
    def smallSize(self, url, filePath):
        file = StringIO(urllib2.urlopen(url).read())
        Imgfile = Image.open(file).convert('RGB')
        size = (Imgfile.size[0]/4,Imgfile.size[1]/4)
        smallImg = Imgfile.resize(size, Image.ANTIALIAS)#改变尺寸  
        smallImg.save(filePath, "JPEG", quality = 90)
        
class CanvasImg():
    def __init__(self, _root, _path):
        self.parent = _root
        self.imgPath = _path
        self.imgob = Image.open(self.imgPath)
        self.size = self.imgob.size
        self.PhotoImage = ImageTk.PhotoImage(file = self.imgPath)
        self.canv = Canvas(self.parent, bg = 'white', width = self.size[0], height = self.size[1])
            
    def addImg(self, _row, _column):
        self.canv.create_image((self.size[0]/2,self.size[1]/2), image = self.PhotoImage)
        self.canv.bind("<Button-1>", self.addFunctionClick)
        self.canv.grid(row=_row, column=_column, columnspan=1, sticky=W + E + N + S, padx=1, pady=1);
        self.parent.update_idletasks()
    
    def addFunctionClick(self, event):
        print 'u click'
        output = StringIO()
        self.imgob.convert("RGB").save(output, "BMP")  
        data = output.getvalue()[14:]  
        output.close()
        win32clipboard.OpenClipboard()  
        try:  
            # Unicode tests  
            win32clipboard.EmptyClipboard()  
            win32clipboard.SetClipboardData(win32con.CF_DIB, data)  
        except:  
            traceback.print_exc()  
        finally:  
            win32clipboard.CloseClipboard()
            
def showAllEmotion(_parent, _num, _keyword):
    inst = {}
    row = 0
    column = 0
    i = 0
    while(i < _num):
        inst[str(i)] = CanvasImg(_parent, BASE_PATH + _keyword+'/' + str(i)+'.jpg')
        inst[str(i)].addImg(row,column)
        # print row,column
        i += 1
        column += 1
        if(column == 8):
            row += 1
            column = 0
    root.mainloop()
    
if __name__ == '__main__':
    root = Tk()
    root.title("司机开车工具")  # 设置窗口标题
    
    UIBtn = SearchImg(root)
    UIBtn.ShowSearchUi()
    
    root.mainloop()
    